//
//  WeiboNetWorkingTools.swift
//  MyWeibo
//
//  Created by tanchao on 15/7/31.
//  Copyright © 2015年 chaoren. All rights reserved.
//

import UIKit
import AFNetworking
///错误捕获的类别标识
private let WeiboErrorDomainName = "com.chaoren.error.network"
private enum WeiboError : Int{
    case emptyDataError = -1
    case emptyTokenError = -2
    
    private var errorDescription : String{
        switch self{
        case .emptyDataError : return "空数据"
        case .emptyTokenError : return "Token 为空"
        }
    }
    private func error()->NSError{
        return NSError(domain: WeiboErrorDomainName, code: rawValue, userInfo: [WeiboErrorDomainName :errorDescription])
    }
}
/// 网络请求方式枚举
///
/// - GET:  get方法
/// - POST: post方法
private enum WeiboNetWorkToolMethod : String{

    case GET = "GET"
    case POST = "POST"
}
/// 网络工具
class WeiboNetWorkingTools: AFHTTPSessionManager {
//  MARK:- 应用程序信息
    private let clientID = "230035099"
    private let appSecret="55c9ed718d09f7d0c2e3c168782e1ad9"
    let redirectUri = "http://www.baidu.com"

//  MARK:- 单例
    static let sharedNetWorkingTools :WeiboNetWorkingTools = {
        let BASEURL = NSURL(string: "https://api.weibo.com/")!
        let tools = WeiboNetWorkingTools(baseURL: BASEURL)
        tools.responseSerializer.acceptableContentTypes = NSSet(objects:"application/json", "text/json", "text/javascript", "text/plain") as Set<NSObject>
        return tools
        }()
    /// 网络访问回调
    typealias WeiboNetWorkCallBack = (result:[String:AnyObject]?,error:NSError?)->()
    //    MARK:- OAuth授权
    // - returns: OAuth授权地址
    func oathUrl()->NSURL{
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(clientID)&redirect_uri=\(redirectUri)"
        return NSURL(string: urlStr)!
    }
    //  MARK:- 获取token
    func loadAccesstoken(CODE code:String,FINISHED finished:WeiboNetWorkCallBack){
        let urlStr = "https://api.weibo.com/oauth2/access_token"
        let params = ["client_id":clientID,
            "client_secret":appSecret,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":redirectUri,
        ]
        request(WeiboNetWorkToolMethod.POST, urlStr: urlStr, params: params, finished: finished)
    }
    //  MARK:- 加载用户数据
    func loadUserInfo(uid: String,finished:WeiboNetWorkCallBack){
        guard var params = tokenDict(finished) else{
            return
        }
        params["uid"] = uid
        let urlstr = "2/users/show.json"
        request(WeiboNetWorkToolMethod.GET, urlStr: urlstr, params: params, finished: finished)
    }
    

    // MARK:- 加载微博
    func loadStatus(since_id:Int?,max_id:Int?,finished:WeiboNetWorkCallBack){
    
        guard var params = tokenDict(finished) else{
            return
        }
        if since_id > 0{
            params["since_id"] = since_id
        }
        if max_id > 0{
            params["max_id"] = max_id! - 1
        }
        let urlStr = "/2/statuses/home_timeline.json"
        request(WeiboNetWorkToolMethod.GET, urlStr: urlStr, params: params, finished: finished)
    }
    // MARK:- 检查生成token字典
    /// 检查并获取touken
    ///
    /// - parameter finished: 回调函数
    ///
    /// - returns:[String : AnyObject]
    private func tokenDict(finished:WeiboNetWorkCallBack)-> [String : AnyObject]? {
        if UserAccount.sharedAccount?.access_token == nil{
            let error = WeiboError.emptyTokenError.error()
            print(error)
            finished(result: nil, error:error)
            return nil
        }
        return ["access_token":UserAccount.sharedAccount!.access_token!]
    }
    
    /// AFN网络请求
    ///
    /// - parameter method  : HTTP方法 GET/POST
    /// - parameter urlStr  : URL 字符串
    /// - parameter params  : 字典参数
    /// - parameter finished: 结束回调
    private func request(method: WeiboNetWorkToolMethod,urlStr:String,params:[String : AnyObject],finished:WeiboNetWorkCallBack){
//        成功回调
        let successCallBack :(NSURLSessionDataTask!, AnyObject! ) ->Void = { (_, JSON) -> Void in
            if let result = JSON as? [String : AnyObject]{
                finished(result: result, error: nil)
            }else{
                print("没有错误，没有数据\(method) request \(urlStr)")
                finished(result: nil, error: WeiboError.emptyDataError.error())
            }
        }
//        失败回调
        
        let failureCallBack : (NSURLSessionDataTask!,NSError!) ->Void = { (_, error) -> Void in
            finished(result: nil, error: error)
        }
//        print(baseURL)
//        print(urlStr)
//        print(params)
        switch method{
        case .GET:
            GET(urlStr, parameters: params, success: successCallBack, failure: failureCallBack)
        case .POST:
            POST(urlStr, parameters: params, success: successCallBack, failure: failureCallBack)
        }
   
    }
    
}
